/*
 * Created by IntelliJ IDEA.
 * User: amrk
 * Date: 10/06/2004
 * Time: 20:58:23
 */
package com.talios.jira.settings.projects;

import com.talios.jira.browser.JiraProjectDetails;

import javax.swing.*;
import java.util.List;

public class ProjectComboBoxModel extends DefaultComboBoxModel {
    private List projectList;

    public ProjectComboBoxModel(List projectList) {
        this.projectList = projectList;
    }

    // implements javax.swing.ListModel
    public int getSize() {
        return projectList == null ? 0 : projectList.size();
    }

    // implements javax.swing.ListModel
    public Object getElementAt(int index) {
        JiraProjectDetails jiraProjectDetails = (JiraProjectDetails) projectList.get(index);
        if (jiraProjectDetails != null) {
            return jiraProjectDetails.getProjectName();
        } else {
            return "";
        }
    }

    public int getIndexOfProjectId(Object anObject) {
        String projectId = (String) anObject;

        int index = 0;
        for (Object aProjectList : projectList) {
            JiraProjectDetails jiraProjectDetails = (JiraProjectDetails) aProjectList;
            if (projectId.equals(jiraProjectDetails.getProjectId())) {
                return index;
            }

            index++;
        }

        return -1;
    }

    public int getIndexOfProjectName(Object anObject) {
        String projectName = (String) anObject;

        int index = 0;
        for (Object aProjectList : projectList) {
            JiraProjectDetails jiraProjectDetails = (JiraProjectDetails) aProjectList;
            if (projectName.equals(jiraProjectDetails.getProjectName())) {
                return index;
            }

            index++;
        }

        return -1;
    }

    public void setSelectedProject(JiraProjectDetails project) {

        int index = getIndexOfProjectId(project.getProjectId());
        if (index != -1) {
            JiraProjectDetails jiraProjectDetails = (JiraProjectDetails) projectList.get(index);
            setSelectedItem(jiraProjectDetails);
        }
    }

    public String getIdOfProjectName(Object selectedItem) {
        int index = getIndexOfProjectName(selectedItem);
        JiraProjectDetails jiraProjectDetails = (JiraProjectDetails) projectList.get(index);
        return jiraProjectDetails.getProjectId();
    }

    public String getKeyOfProjectName(Object selectedItem) {
        int index = getIndexOfProjectName(selectedItem);
        JiraProjectDetails jiraProjectDetails = (JiraProjectDetails) projectList.get(index);
        return jiraProjectDetails.getProjectKey();
    }

    public JiraProjectDetails getSelectedProject() {
        int index = getIndexOfProjectName(getSelectedItem());
        JiraProjectDetails jiraProjectDetails = (JiraProjectDetails) projectList.get(index);
        return jiraProjectDetails;
    }
}